package com.bnz.service.impl;

import cn.hutool.core.util.StrUtil;
import com.bnz.mapper.StudentMapper;
import com.bnz.pojo.PageResult;
import com.bnz.pojo.Student;
import com.bnz.pojo.StudentExample;
import com.bnz.pojo.StudentVo;
import com.bnz.service.StudentService;
import com.bnz.util.MyBatisUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

/**
 * 类名：
 * 作者：WF
 * 功能：
 */
public class StudentServiceImpl implements StudentService {
	//1. 列表所有学生
	@Override
	public List<Student> findAll() {
		try(SqlSession session = MyBatisUtil.getSqlSession()){
			StudentMapper mapper = session.getMapper(StudentMapper.class);
			List<Student> students = mapper.selectByExample(null);
			return students;
		}
	}
	//2. 查询单个学生
	@Override
	public Student findById(int id) {
		try(SqlSession session = MyBatisUtil.getSqlSession()){
			StudentMapper mapper = session.getMapper(StudentMapper.class);
			return mapper.selectByPrimaryKey(id);
		}
	}

	//3. 添加学生
	@Override
	public void insert(Student stud) {
		try(SqlSession session = MyBatisUtil.getSqlSession()){
			StudentMapper mapper = session.getMapper(StudentMapper.class);
			mapper.insert(stud);
		}
	}

	//4. 条件查询带分页
	@Override
	public PageResult<Student> search(int page, int pagesize, StudentVo vo) {
		PageHelper.startPage(page,pagesize);
		//4.1 进行实例查询
		if(vo != null){
			try(SqlSession session = MyBatisUtil.getSqlSession()){
				//4.1.1 得到StudentMapper对象
				StudentMapper mapper = session.getMapper(StudentMapper.class);
				//4.1.2 得到查询实例
				StudentExample example = new StudentExample();
				//4.1.3 得到查询条件
				StudentExample.Criteria criteria = example.createCriteria();
				//4.1.4 封装查询条件
				if(StrUtil.isNotBlank(vo.getSname())){
					criteria.andSnameLike("%" + vo.getSname() + "%");
				}
				if(StrUtil.isNotBlank(vo.getAddr())){
					criteria.andAddrLike("%" + vo.getAddr() + "%");
				}
				if(vo.getCid() != 0){
					criteria.andCidEqualTo(vo.getCid());
				}
				//4.1.5 开始条件查询
				List<Student> students = mapper.selectByExample(example);
				//4.1.6 转换为Page对象
				Page<Student> studentPage = (Page<Student>) students;
				//4.1.7 返回
				return new PageResult<>(studentPage.getPages(),studentPage.getResult());
			}

		}
		return null;
	}
}
